<?php

class Roles_AclModulesPermissions extends Zwei_Db_Table
{
    protected $_name = "acl_permissions";
    protected $_name_modules = "acl_modules";
    protected $_name_actions = "web_permisions";
    protected $_adapter = "dn";
    protected $_related = NULL;
    protected $_roles_id;
    
    
    public function select() 
    {
        $webPermissions = new PermissionsModel();
        $select = $webPermissions->select();
        $select->order("title");
        
        $actions = $this->fetchAll($select);
        
        $aSelect = array();
        foreach ($actions as $v) {
            $selectTmp = new Zend_Db_Table_Select($this);
            $selectTmp->setIntegrityCheck(false);
            
            $selectTmp->distinct();
            $selectTmp->from($this->_name_modules, 
                array(
                    'acl_modules_id' => 'id', 
                    'title', 
                    'module',
                    'permission' => new Zend_Db_Expr("'$v->id'"),
                    'permission_title' => new Zend_Db_Expr("'$v->title'")
                )
            );
            $selectTmp->joinLeft(array('parent'=>$this->_name_modules), "$this->_name_modules.parent_id = parent.id",
            array("module_title"=>new Zend_Db_Expr("IF($this->_name_modules.parent_id > 0, CONCAT(parent.title, '->', $this->_name_modules.title), $this->_name_modules.title)")));
            
            if (!empty($this->_roles_id)) {
                $op = ($this->_related === true) ? "=" : "!=";
                $selectTmp->joinLeft($this->_name, "$this->_name_modules.id = $this->_name.{$this->_name_modules}_id", array('acl_roles_id'));
                $selectTmp->where("acl_roles_id $op ?", $this->_roles_id);
            }
            $selectTmp->where("$this->_name_modules.approved = ?", "1");
            //Si no pertenece al role_id 1, no puede ver módulos root
            if ($this->_user_info->acl_roles_id != '1') $selectTmp->where("$this->_name.root != ?", "1");
            $aSelect[] = $selectTmp;
        }
        
        $select = new Zend_Db_Table_Select($this);

        $select->union($aSelect);

        return $select;
    }
    
    /**
     * 
     * @param boolean
     */
    public function setRelated($value)
    {
        $this->_related = $value;
    }
    
    public function setRolesId($value)
    {
        $this->_roles_id = $value;
    }
    
    
}